import cv2
import numpy as np

from _0work_tools import cv_show
from _02threshold import thresh_operate
from _03fulfill import fulfill_border
from _0work_tools import box_filter_factor

"""
@Project: pythonPro1
@Name: _05corrosion.py
@Author: linxin_liu
@Date: 2022/10/15 18:03
腐蚀、膨胀、开闭操作、边界
"""


# 腐蚀
def corrosion_filter(img, size):
    box_filter = box_filter_factor(size, 255)
    # 先将图片加大一圈，那一圈值为0。边界，为了腐蚀，要和目标不一样，才会腐蚀
    full_imag = fulfill_border(img, 1, 1, 1, 1, 'black')
    # 开始循环遍历
    for i in range(len(img)):  # 大的双循环只需要遍历 原始图像的高*宽 次。
        for j in range(len((img[0]))):
            yes = + \
                      full_imag[i][j] == box_filter[0][0] and full_imag[i][j + 1] == box_filter[0][1] and + \
                      full_imag[i][j + 2] == box_filter[0][2] and full_imag[i + 1][j] == box_filter[1][0] and + \
                      full_imag[i + 1][j + 1] == box_filter[1][1] and full_imag[i + 1][j + 2] == box_filter[1][2] and + \
                      full_imag[i + 2][j] == box_filter[2][0] and full_imag[i + 2][j + 1] == box_filter[2][1] and + \
                      full_imag[i + 2][j + 2] == box_filter[2][2]
            if yes:
                img[i][j] = 255
            else:
                img[i][j] = 0
    return img


# 膨胀
def expand_filter(img, size):
    full_imag = fulfill_border(img, 1, 1, 1, 1, 'black')
    h = len(full_imag)
    w = len(full_imag[0])
    full_imag_temp = np.arange(0, h * w)
    full_imag_final = full_imag_temp.reshape((h, w))  # 一维转二维
    for i in range(0, h):
        for j in range(0, w):
            full_imag_final[i][j] = 0  # 新建一个大的图片，全为0，然后被遍历赋值。
    # 开始循环遍历。过滤盒是2*2的。
    for i in range(0, len(img) + 1):  # 大的双循环只需要遍历 原始图像的(高+1)*(宽+1) 次。
        for j in range(0, len((img[0])) + 1):
            yes = full_imag[i][j] == 255 or full_imag[i][j + 1] == 255 or full_imag[i + 1][j] == 255 or \
                  full_imag[i + 1][j + 1] == 255
            if yes:
                full_imag_final[i][j] = 255
                full_imag_final[i][j + 1] = 255
                full_imag_final[i + 1][j] = 255
                full_imag_final[i + 1][j + 1] = 255
    # 将大的图片的最外圈一圈切割。
    img = full_imag_final[1:len(full_imag_final) - 1, 1:len(full_imag_final[0]) - 1]
    return np.array(img, dtype=np.uint8)  # 修改数据类型。


if __name__ == '__main__':
    img_original = cv2.imread('D:/tools/image_operation/AM.png', cv2.IMREAD_GRAYSCALE)
    binary_img = thresh_operate(127, img_original, 'Binary')
    after_cor = corrosion_filter(binary_img, [3, 3])

    img_original = cv2.imread('D:/tools/image_operation/AM.png', cv2.IMREAD_GRAYSCALE)
    binary_img = thresh_operate(127, img_original, 'Binary')
    after_ex = expand_filter(binary_img, [2, 2])

    outline = after_ex[:, :] - after_cor[:, :]  # 轮廓
    cv_show('c', outline, 8000)
    # cv2.imwrite("D:/tools/image_operation/lenaNoise_a.png", outline)
    # print(outline)
